package com.example.administrator.common.base;

import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 全局公共类, 封装：屏幕宽高获取，单位转换，主线程运行等
 * Created by Administrator on 2017/11/28.
 * @author LQW
 */
public class Global {
	
	public static Context mContext;
	/** 屏幕密度 */
	public static float mDensity;
	/** 屏幕宽度 */
	public static float mScreenWidth;
	/** 屏幕高度 */
	public static float mScreenHeight;

	public static void init(Context context) {
		mContext = context;
		initScreenSize();
	}

	private static void initScreenSize() {
		DisplayMetrics dm = mContext.getResources().getDisplayMetrics();
		mDensity = dm.density;
		mScreenHeight = dm.heightPixels;
		mScreenWidth = dm.widthPixels;
	}

	/** 单位转换 */
	public static int dp2px(int dp) {
		return (int) (dp * mDensity + 0.5f);
	}

	/** 填充布局 */
	public static View inflate(int layoutResID, ViewGroup parent) {
		return LayoutInflater.from(mContext).inflate(layoutResID, parent, false);
	}

	/** 填充布局 */
	public static View inflate(int layoutResID) {
		return inflate(layoutResID, null);
	}

	private static Handler mHandler = new Handler(Looper.getMainLooper());

	public static Handler getMainHandler() {
		return mHandler;
	}
	
	/**
	 * 判断当前线程是否是主线程
	 * @return true表示当前是在主线程中运行
	 */
	public static boolean isMainThread() {
		// 主线程的Looper == 当前线程的Looper
		return Looper.getMainLooper() == Looper.myLooper();
	}

	/** 在主线程运行 */
	public static void runOnMainThread(Runnable run) {
		if (isMainThread()) {
			run.run();
		} else {
			mHandler.post(run);
		}
	}
	
	private static Toast mToast;

	/**
	 * showToast，可以在子线程中调用
	 *
	 * @param msg toast内容
	 */
	public static void showToast(final String msg) {
		runOnMainThread(new Runnable() {
			@Override
			public void run() {
				if (mToast == null) {
					mToast = Toast.makeText(mContext, msg, Toast.LENGTH_SHORT);
				}
				mToast.setText(msg);
				mToast.show();
			}
		});
	}

//////////////////////////////////////////////////////////////////////////////////
	private static Toast shortToast = null;

	public static void makeShortText(String msg, Context context) {
		if (context == null) {
			return;
		}

		if (shortToast == null) {
			shortToast = Toast.makeText(context, msg, Toast.LENGTH_SHORT);
		} else {
			shortToast.setText(msg);
		}
		shortToast.show();
	}


	private static Toast longToast = null;

	public static void makeLongText(String msg, Context context) {
		if (context == null) {
			return;
		}

		if (longToast == null) {
			longToast = Toast.makeText(context, msg, Toast.LENGTH_LONG);
		} else {
			longToast.setText(msg);
		}
		longToast.show();
	}



	public static void showLong(Context context,String msg){
		makeLongText(msg, context);
	}

	public static void showLong(Context context,int id){
		makeLongText(context.getResources().getString(id), context);
	}

	public static void showShort(Context context,String msg){
		makeShortText(msg, context);
	}

	public static void showShort(Context context,int id){
		makeShortText(context.getResources().getString(id), context);
	}


	public static void showCenterToast(Context context, String msg) {
		Toast toast = Toast.makeText(context, msg,  Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}
	///////////////////////////////////////////////////////////////////////////////////
	//=============沉侵式==(begin)=================

	private static View mStatusBarView;

	/** 设置状态栏为透明色： 全屏沉侵式效果 */
	public static void setNoStatusBarFullMode(Activity activity) {
		// sdk 4.4： 只能设置为半透明
		if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
			Window window = activity.getWindow();
			window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

			if (mStatusBarView != null) {
				ViewGroup root = (ViewGroup) activity.findViewById(android.R.id.content);
				root.removeView(mStatusBarView);
			}
			return;
		}

		// sdk 5.x : 透明
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			Window window = activity.getWindow();
			// TRANSLUCENT: 半透明
			// transparent: 透明
			// NAVIGATION: 虚拟按键，导航栏
			window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			window.setStatusBarColor(Color.TRANSPARENT);
			return;
		}
	}

	/** 设置控件的paddingTop, 使它不被StatusBar覆盖 */
	public static void setStatusBarPadding(View view) {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
			int marginTop = getStatusBarHeight(view.getContext());
			view.setPadding(view.getPaddingLeft(), marginTop,
					view.getPaddingRight(), view.getPaddingBottom());
			return;
		}
	}

	/**
	 * 通过反射的方式获取状态栏高度，
	 */
	public static int getStatusBarHeight(Context context) {
		try {
			// 无法访问
//			int id = com.android.internal.R.dimen.status_bar_height;
//			int height = context.getResources().getDimensionPixelSize(id);
//			return  height;

			Class<?> clazz = Class.forName("com.android.internal.R$dimen");
			Object obj = clazz.newInstance();
			Field field = clazz.getField("status_bar_height");
			int id = Integer.parseInt(field.get(obj).toString());
			return context.getResources().getDimensionPixelSize(id);

		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("-------无法获取到状态栏高度");
		}
		return dp2px(24);
	}

	public static void setStatusBarColor(Activity activity, int statusColor) {
		// sdk 4.4
		if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
			ViewGroup root = (ViewGroup) activity.findViewById(android.R.id.content);
			if (mStatusBarView == null) {
				mStatusBarView = new View(activity);
				mStatusBarView.setBackgroundColor(statusColor);
			} else {
				// 先解除父子控件关系，否则重复把一个控件多次
				// 添加到其它父控件中会出错
				ViewParent parent = mStatusBarView.getParent();
				if (parent != null) {
					ViewGroup viewGroup = (ViewGroup) parent;
					if (viewGroup != null)
						viewGroup.removeView(mStatusBarView);
				}
			}
			ViewGroup.LayoutParams param = new ViewGroup.LayoutParams(
					ViewGroup.LayoutParams.MATCH_PARENT,
					getStatusBarHeight(activity));
			root.addView(mStatusBarView, param);
			return;
		}

		// sdk 5.x
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
			activity.getWindow().setStatusBarColor(statusColor);
			return;
		}
	}

	/** 导航栏的高度 */
	public static int getNavigationBarHeight(Context context) {
		Resources resources = context.getResources();
		int rid = resources.getIdentifier("config_showNavigationBar", "bool", "android");
		if (rid != 0) {
			int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
			return resources.getDimensionPixelSize(resourceId);
		}
		return 0;
	}

	//获取是否存在NavigationBar
	public static boolean hasNavigationBar(Context context) {
		boolean hasNavigationBar = false;
		Resources rs = context.getResources();
		int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
		if (id > 0) {
			hasNavigationBar = rs.getBoolean(id);
		}
		try {
			Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
			Method m = systemPropertiesClass.getMethod("get", String.class);
			String navBarOverride = (String) m.invoke(
					systemPropertiesClass, "qemu.hw.mainkeys");
			if ("1".equals(navBarOverride)) {
				hasNavigationBar = false;
			} else if ("0".equals(navBarOverride)) {
				hasNavigationBar = true;
			}
		} catch (Exception e) {
		}
		return hasNavigationBar;
	}

	//=============沉侵式==(end)=================
}
